package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    SetmealDishService setmealDishService;
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);
    }
    @Autowired
    SetmealMapper setmealMapper;

    @Override
    public Page<SetmealDto> pageSetmealDto(Integer page, Integer pageSize, String name) {

        Page<SetmealDto> Pageinfo = new Page<>(page, pageSize);
        return setmealMapper.pageSetmealDto(Pageinfo,name);
    }

    @Override
    public void deleteByIds(Long[] ids) {
        //1.判断是否是停售的，如果是的，就抛异常
        Integer count = this.lambdaQuery()
                .in(Setmeal::getId, ids)
                .eq(Setmeal::getStatus,1)
                .count();
        if (count>0){
            throw new CustomerException("有套餐在售，无法删除");
        }
        //2.删除套餐信息
        this.removeByIds(Arrays.asList(ids));
        //3.删除套餐菜品信息
        setmealDishService.lambdaUpdate()
                .in(SetmealDish::getSetmealId,ids)
                .remove();
    }

    @Override
    public SetmealDto getSetmealDtoBYId(Long id) {
        return setmealMapper.getSetmealDtoBYId(id);
    }

    //根据页面返回的数据进行修改
    @Override
    public void getdeleteById(SetmealDto setmealDto) {
        //1.修改套餐信息
        this.updateById(setmealDto);
        //2.修改菜品信息
        setmealDto.getId();
        //2.1先把菜品中的数据根据ID删除
        setmealDishService.lambdaUpdate()
                .eq(SetmealDish::getSetmealId,setmealDto.getId())
                .remove();
        //2.2把数据重新添加到套餐菜品表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //2.3把套餐ID设置到套餐菜品表
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);

    }
}
